#include <stdio.h>
#include <stdlib.h>

// 定义卷积神经网络的结构
typedef struct {
    float** weights;   // 权重矩阵
    float* biases;     // 偏置向量
    int numFilters;    // 过滤器数量
    int filterSize;    // 过滤器大小
    int inputSize;     // 输入大小
} ConvNet;

// 创建卷积神经网络模型
ConvNet* createConvNet(int numFilters, int filterSize, int inputSize) {
    ConvNet* net = (ConvNet*)malloc(sizeof(ConvNet));
    net->numFilters = numFilters;
    net->filterSize = filterSize;
    net->inputSize = inputSize;
    
    // 初始化权重矩阵和偏置向量
    net->weights = (float**)malloc(numFilters * sizeof(float*));
    for (int i = 0; i < numFilters; i++) {
        net->weights[i] = (float*)malloc(filterSize * filterSize * sizeof(float));
        for (int j = 0; j < filterSize * filterSize; j++) {
            net->weights[i][j] = (float)rand() / RAND_MAX;  // 随机初始化权重
        }
    }
    
    net->biases = (float*)malloc(numFilters * sizeof(float));
    for (int i = 0; i < numFilters; i++) {
        net->biases[i] = 0.0;  // 初始化偏置为0
    }
    
    return net;
}

// 使用卷积神经网络进行前向传播
void forwardPropagation(ConvNet* net, float* input, float* output) {
    int outputSize = net->inputSize - net->filterSize + 1;  // 计算输出大小
    
    for (int i = 0; i < net->numFilters; i++) {
        for (int j = 0; j < outputSize; j++) {
            for (int k = 0; k < outputSize; k++) {
                float sum = 0.0;
                for (int m = 0; m < net->filterSize; m++) {
                    for (int n = 0; n < net->filterSize; n++) {
                        sum += input[(j + m) * net->inputSize + (k + n)] * net->weights[i][m * net->filterSize + n];
                    }
                }
                output[i * outputSize * outputSize + j * outputSize + k] = sum + net->biases[i];
            }
        }
    }
}

int main() {
    // 创建一个卷积神经网络模型
    const int numFilters = 3;
    const int filterSize = 3;
    const int inputSize = 5;
    ConvNet* net = createConvNet(numFilters, filterSize, inputSize);
    
    // 输入数据
    float input[5 * 5] =                 {0.5, 0.6, 0.7, 0.8, 0.9,
                                          0.1, 0.2, 0.3, 0.4, 0.5,
                                          0.6, 0.7, 0.8, 0.9, 1.0,
                                          0.1, 0.2, 0.3, 0.4, 0.5};

    // 计算输出
    int outputSize = inputSize - filterSize + 1;
    float output[numFilters * outputSize * outputSize];
    forwardPropagation(net, input, output);

    // 打印输出
    printf("Output:\n");
    for (int i = 0; i < numFilters; i++) {
        printf("Filter %d:\n", i);
        for (int j = 0; j < outputSize; j++) {
            for (int k = 0; k < outputSize; k++) {
                printf("%.2f ", output[i * outputSize * outputSize + j * outputSize + k]);
            }
            printf("\n");
        }
        printf("\n");
    }

    // 释放内存
    for (int i = 0; i < numFilters; i++) {
        free(net->weights[i]);
    }
    free(net->weights);
    free(net->biases);
    free(net);

    return 0;
}


